#pragma once
#include <iostream>
#include <queue>
#include <vector>
#include <functional>
#include <pthread.h>
#include "Log.hpp"
#include "Thread.hpp"
using namespace ThreadModule;

static const int defaultSize = 3;

template <class T>
class ThreadPool
{
private:
    bool QueueEmpty()
    {
        return _queue.empty();
    }
    void Lock()
    {
        pthread_mutex_lock(&_mutex);
    }
    void UnLock()
    {
        pthread_mutex_unlock(&_mutex);
    }
    void Wait()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    void WakeUp()
    {
        pthread_cond_signal(&_cond);
    }
    void WakeAll()
    {
        pthread_cond_broadcast(&_cond);
    }
    ThreadPool(int size = defaultSize)
        : _threadnum(size), _isrunning(false), _waitnum(0)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
        LOG(INFO, "threadpoll Construct()\n");
    }
    void HandlerTask(std::string name)
    {
        LOG(INFO, "%s is running...\n", name.c_str());
        while (true)
        {
            Lock();
            while (_isrunning && QueueEmpty())
            {
                _waitnum++;
                Wait();
                _waitnum--;
            }
            if (!_isrunning && QueueEmpty())
            {
                UnLock();
                break;
            }
            T t = _queue.front();
            _queue.pop();
            UnLock();

            LOG(INFO, "%s get a task\n", name.c_str(), t);
            t();
        }
    }
    void InitPool()
    {
        for (int i = 0; i < _threadnum; i++)
        {
            std::string name = "thread-" + std::to_string(i + 1);
            _threads.emplace_back(std::bind(&ThreadPool::HandlerTask, this, std::placeholders::_1), name);
            LOG(INFO, "init %s done\n", name.c_str());
        }
    }
    void Start()
    {
        _isrunning = true;
        for (auto &thread : _threads)
        {
            thread.Start();
        }
    }
    ThreadPool(const ThreadPool<T> &) = delete;
    ThreadPool<T> &operator=(const ThreadPool<T> &) = delete;

public:
    static ThreadPool<T> *GetInstance()
    {
        if (nullptr == _instance)
        {
            LockGuard lg(_gMutex);
            if (nullptr == _instance)
            {
                _instance = new ThreadPool<T>();
                _instance->InitPool();
                _instance->Start();
                LOG(INFO, "create instance success...\n");
            }
        }
        return _instance;
    }

    void Stop()
    {
        Lock();
        _isrunning = false;
        WakeAll();
        UnLock();
    }
    void WaitAll()
    {
        for (auto &thread : _threads)
        {
            thread.Join();
            LOG(INFO, "%s is quit\n", thread.name().c_str());
        }
    }
    bool Enqueue(const T &t)
    {
        bool ret = false;
        Lock();
        if (_isrunning)
        {
            _queue.push(t);
            if (_waitnum > 0)
                WakeUp();
            LOG(INFO, "enqueue task success\n");
            ret = true;
        }
        UnLock();
        return ret;
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

private:
    int _threadnum;
    std::vector<Thread> _threads;
    std::queue<T> _queue;
    bool _isrunning;
    int _waitnum;

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    // 单例
    static ThreadPool<T> *_instance;
    static pthread_mutex_t _gMutex;
};

template <class T>
ThreadPool<T> *ThreadPool<T>::_instance = nullptr;

template <class T>
pthread_mutex_t ThreadPool<T>::_gMutex = PTHREAD_MUTEX_INITIALIZER;